import {
  article_article,
  article_change,
  article_check,
  del_articles,
  getArticles,
} from '@/services/ant-design-pro/miniModel2';
import { DeleteOutlined, SaveOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { Button, Input, message, Modal, Pagination, Popconfirm, Spin } from 'antd';
import React, { useEffect, useState } from 'react';
import './index.less';
const MiniModel2: React.FC = () => {
  const [load, setLoad] = useState<boolean>(false); //当前选中文章的索引
  const [list, setList] = useState<any>([]); //文章列表
  const [pageSize, setPageSize] = useState<any>({ page: 1, per_page: 10 }); //文章翻页
  const [total, setTotal] = useState<number>(0); //文章总数
  const [active, setActive] = useState<number>(0); //当前选中文章的索引
  const [nextActive, setNextActive] = useState<number>(-1); //当前选中文章的索引
  const [curArticle, setCurArticle] = useState<any>({
    title: '',
    main_body: '',
    id: '',
  }); //当前显示的文章

  // const [isEdit, setIsEdit] = useState(false); //是否编辑过内容
  const [isModalOpen, setIsModalOpen] = useState(false); //modal提示框

  const [patternIpt, setPatternIpt] = useState<string>(''); //要替换的目标
  const [replaceIpt, setReplaceIpt] = useState<string>(''); //替换内容的输入框
  const [title, setTitle] = useState<string>(''); //标题
  const { TextArea } = Input;

  useEffect(() => {
    document.title = '人工清洗文档'; //设置标题
  }, []);

  //编辑文章内容
  const articleChange = (e: any) => {
    setCurArticle({
      ...curArticle,
      main_body: e.target.value,
    });
    // setIsEdit(true);
  };

  //目标内容change
  const patternIptChange = (e: any) => {
    setPatternIpt(e.target.value);
  };
  //替换内容change
  const replaceIptChange = (e: any) => {
    setReplaceIpt(e.target.value);
  };

  //切换文章
  const toggleActive = (item: any, index: any) => {
    if (active === index) {
      setNextActive(index);
      // eslint-disable-next-line @typescript-eslint/no-use-before-define
      handleOk();
    } else {
      setActive(index);
      setCurArticle(list[index]);
      setTitle(list[index]?.title);
    }
  };
  //获取文章
  const handleGetArticles = async () => {
    setLoad(true);
    let res = await getArticles({
      page: pageSize.page,
      per_page: pageSize.per_page,
      status: 'cleaning',
    });
    if (res.code === 0) {
      setLoad(false);
      setTotal(res?.data?.total_count || 0);
      setList(res?.data?.articles || []);
      if (res?.data?.articles?.length > 0) {
        setCurArticle(res?.data?.articles[active]);
        setTitle(res?.data?.articles[active]?.title);
      } else {
        setCurArticle({
          title: '',
          main_body: '',
          id: '',
        });
        setTitle('');
      }
    } else {
      message.error(res.msg);
      setLoad(false);
    }
  };

  //翻页
  const changePageSize = async (page: any, pageSize: any) => {
    setPageSize({
      page: page,
      per_page: pageSize,
    });
  };

  //获取文章内容
  useEffect(() => {
    handleGetArticles();
  }, [pageSize]);

  //替换操作
  const handleOperate = async () => {
    let body = {
      article_id: curArticle.id,
      pattern: patternIpt,
      replace: replaceIpt,
    };
    let res = await article_change(body);
    if (res.code === 0) {
      message.success('替换成功');
      handleGetArticles();
    } else {
      message.error(res.msg);
    }
  };

  //确认完成
  // const handleSubmit = async () => {
  //   setNextActive(-1); //直接点确定完成的 下一个索引按照顺序
  //   setIsModalOpen(true);
  // };
  //确定清洗
  const handleOk = async () => {
    if (!curArticle.id) {
      message.warning('当前暂无选中的文章');
      return;
    }

    setNextActive(-1);
    // setIsModalOpen(false);
    let body = {
      article_id: curArticle.id,
    };
    let res = await article_check(body);
    if (res.code === 0) {
      message.success('清洗完成');
      setIsModalOpen(false);
      handleGetArticles();
      //如果是从切换文档来的确定 则要隐藏弹窗后 切换到当前要切换到文档
      if (nextActive !== -1) {
        let nextAct = nextActive - 1 < 0 ? 0 : nextActive - 1;
        console.log(nextAct);
        setActive(nextAct);
        setCurArticle(list[nextAct]);
      } else {
      }
    } else {
      message.error(res.msg);
      setIsModalOpen(false);
    }
  };
  //取消
  const handleCancel = () => {
    setIsModalOpen(false);
    //如果是从切换文档来的取消 则要隐藏弹窗后 切换到当前要切换到文档
    if (nextActive !== -1) {
      setActive(nextActive);
      setCurArticle(list[nextActive]);
    }
  };
  //删除该篇文章
  const handleDel = async () => {
    if (!curArticle.id) {
      message.warning('没有可删除的文章');
      return;
    }
    let res = await del_articles({
      article_id: curArticle.id,
    });
    if (res.code === 0) {
      message.success('删除成功');
      handleGetArticles();
    } else {
      message.error(res.msg);
    }
  };
  //编辑该篇文章
  const handleEdit = async () => {
    if (!curArticle.id) {
      message.warning('没有可编辑的文章');
      return;
    }
    let res = await article_article({
      article_id: curArticle.id,
      title: title,
      main_body: curArticle.main_body,
    });
    if (res.code === 0) {
      message.success('编辑保存成功，正在刷新文章');
      handleGetArticles();
    } else {
      message.error(res.msg);
    }
  };
  const titleChange = (e: any) => {
    setTitle(e.target.value);
  };
  const cancel = () => {};

  //去上传文件
  const goToUrl = () => {
    history.push('/miniModel1');
  };
  //去标记文档
  const goToUrl2 = () => {
    history.push('/miniModel3');
  };

  //默认选中文档 来源 领域 地区
  useEffect(() => {
    if (curArticle?.title) {
      setTitle(title);
    }
  }, [curArticle]);
  return (
    <div className="cleanseWrap">
      <div className="cleanseLeft">
        <div className="cleanseLeftTitle">
          已上传的文档
          {load && (
            <div className="loadwrap">
              <Spin />
            </div>
          )}
        </div>
        <div className="cleanseLeftConWrap">
          <div className="cleanseListWrap">
            {list &&
              list.length > 0 &&
              list.map((item: any, index: any) => {
                return (
                  <div
                    key={item.id}
                    onClick={() => toggleActive(item, index)}
                    className={`${active === index ? 'cleanseList active' : 'cleanseList'}`}
                  >
                    {item.title ? item.title : item.main_body}
                  </div>
                );
              })}
          </div>
          <div className="cleansePagination">
            <Pagination size="small" total={total} showQuickJumper onChange={changePageSize} />
          </div>
        </div>
      </div>
      <div className="cleanseMain">
        <div className="articleWrap">
          <div className="articleTitle">
            {/* {curArticle.title} */}
            <Input value={title} onChange={titleChange} />
          </div>
          <div className="articleCont">
            <TextArea
              onChange={articleChange}
              autoSize={{ minRows: 2, maxRows: 2000 }}
              bordered={false}
              // autoSize={true}
              showCount={false}
              value={curArticle?.main_body}
            />
          </div>
        </div>
      </div>
      <div className="cleanseRight">
        <div className="cleanseRightTopBtnBox">
          <Button onClick={goToUrl}>去上传文件</Button>
          <Button onClick={goToUrl2}>去标记文档</Button>
        </div>
        <div className="cleanseRightTitle">请输入目标内容</div>
        <div className="cleanseRightInputBox">
          <TextArea
            onChange={patternIptChange}
            rows={10}
            bordered={false}
            autoSize={false}
            showCount={false}
            value={patternIpt}
          />
        </div>
        <div className="cleanseRightTitle">请输入要替换的内容</div>
        <div className="cleanseRightInputBox">
          <TextArea
            onChange={replaceIptChange}
            rows={9}
            bordered={false}
            autoSize={false}
            showCount={false}
            value={replaceIpt}
          />
          <div className="editBtnBox">
            <Button size="small" type="primary" disabled={!curArticle?.id} onClick={handleOperate}>
              确定
            </Button>
          </div>
        </div>
        <div className="cleanseRightBtnBox">
          <Popconfirm
            title="提示"
            description="确定删除吗?"
            onConfirm={handleDel}
            onCancel={cancel}
            okText="是"
            cancelText="否"
          >
            <Button danger disabled={!curArticle?.id} icon={<DeleteOutlined />}></Button>
          </Popconfirm>
          {/* <Popconfirm
            title="提示"
            description="确定保存编辑的文章吗?"
            onConfirm={handleEdit}
            onCancel={cancel}
            okText="是"
            cancelText="否"
          > */}
          <Button
            className="editsaveBtn"
            onClick={handleEdit}
            type="primary"
            disabled={!curArticle?.id}
            icon={<SaveOutlined />}
          >
            编辑保存
          </Button>
          {/* </Popconfirm> */}

          <Button type="primary" onClick={handleOk} disabled={!curArticle?.id}>
            确认完成
          </Button>
        </div>
      </div>
      <Modal
        title="提示"
        cancelText="取消"
        okText="是"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>是否确认完成对该文档的清洗？</p>
      </Modal>
    </div>
  );
};
export default MiniModel2;
